package com.happy.cat.project.system.service.impl;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.schedule.ScheduleResult;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.happy.cat.common.exception.CustomException;
import com.happy.cat.common.utils.StringFormater;
import com.happy.cat.project.system.service.PushService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.io.Closeable;
import java.io.IOException;
import java.util.TimeZone;

@Slf4j
//@Service("jPushService")
public class JPushServiceImpl implements Closeable, PushService {
	
	@Autowired
	private JPushClient jpushClient;
	
	private final Gson gson=new Gson();
	
	private final String TIME_FORMAT_VALUE ="yyyy-MM-dd HH:mm:ss";
	
//	@Override
//	public boolean updateReceiver(PushReceiverInfo pushReceiverInfo, Set<String> oldTags, Set<String> newTags)  {
//		try {
//			DefaultResult result=jpushClient.updateDeviceTagAlias(pushReceiverInfo.getRegistrationId(), true, true);
//
//			if(result==null) {
//				log.error("result is error");
//				return false;
//			}
//
//			if (log.isInfoEnabled()) {
//				log.info("updateReceiver(String, String, long, List<String>) - updateDeviceTagAlias-clear - registrationId={}, receiverType={}, receiverId={}, tags={}, result={}", pushReceiverInfo.getRegistrationId(), pushReceiverInfo.getReceiverType(), pushReceiverInfo.getReceiverId(), newTags, result); //$NON-NLS-1$
//			}
//
//			if(!result.isResultOK()) {
//				return false;
//			}
//			if(newTags==null){
//				newTags=new TreeSet<>();
//			}else{
//				newTags=new TreeSet<>(newTags);
//			}
//			newTags.add(pushReceiverInfo.getReceiverType());
//			result=jpushClient.updateDeviceTagAlias(pushReceiverInfo.getRegistrationId(), StringFormater.format("{}#{}", pushReceiverInfo.getReceiverType(),pushReceiverInfo.getReceiverId()), newTags, Collections.emptySet());
//
//			if (log.isInfoEnabled()) {
//				log.info("updateReceiver(String, String, long, Set<String>) - updateDeviceTagAlias-add - registrationId={}, receiverType={}, receiverId={}, tags={}, result={}", pushReceiverInfo.getRegistrationId(), pushReceiverInfo.getReceiverType(), pushReceiverInfo.getReceiverId(), newTags, result); //$NON-NLS-1$
//			}
//
//			if(result==null) {
//				return false;
//			}
//
//			return result.isResultOK();
//
//		} catch (APIConnectionException | APIRequestException e) {
//			log.warn("updateReceiver Exception",e);
//			throw new InsLogicException(ApiCode.SYSTEM_RUN_ERROR,e);
//		}
//	}
//
	public PushPayload createUserPush(String title,String message,String userType,Long userId) {
		PushPayload.Builder builder=PushPayload.newBuilder()
									.setPlatform(Platform.all())
									.setNotification(Notification
											.newBuilder()
											.addPlatformNotification(AndroidNotification.newBuilder().setAlert(title).setTitle(message).build())
											.addPlatformNotification(IosNotification.newBuilder().setAlert(title).build())
											.build())
//									.setMessage(Message.newBuilder().setTitle(title).setMsgContent(message).build())
									;
		
		if(userId!=null&&userType!=null) {
			builder.setAudience(Audience.alias(StringFormater.format("{}#{}", userType,userId)));
		}else {
			builder.setAudience(Audience.all());
		}
		
		return builder.build();
	}
	
	
//	public PushPayload createAllUserPush(String title,String message) {
//		return createUserPush(title,message,null,null);
//	}
	

	public PushPayload createGroupPush(String title,String message,String... tags) {
		return PushPayload.newBuilder()
				.setPlatform(Platform.all())
				.setNotification(Notification
						.newBuilder()
						.addPlatformNotification(AndroidNotification.newBuilder().setAlert(title).setTitle(message).build())
						.addPlatformNotification(IosNotification.newBuilder().setAlert(title).build())
						.build())
				.setAudience(tags==null||tags.length==0?Audience.all():Audience.tag(tags))
//				.setMessage(Message.newBuilder().setTitle(title).setMsgContent(message).build())
				.build();
	}
	
	
//	@Override
//	public JsonObject sendPush(String title, String message, PushReceiverInfo pushReceiverInfo)  {
//		try {
//			PushResult result = jpushClient.sendPush(createUserPush(title, message, pushReceiverInfo.getReceiverType(), pushReceiverInfo.getReceiverId()));
//			if(result==null) {
//				return null;
//			}
//
//			if (log.isInfoEnabled()) {
//				log.info("sendPush(String, String, String, Long) - title={}, message={}, userType={}, userId={}, result={}", title, message, pushReceiverInfo.getReceiverType(), pushReceiverInfo.getReceiverId(), result); //$NON-NLS-1$
//			}
//
//			return gson.toJsonTree(result).getAsJsonObject();
//
//
//		} catch (APIConnectionException | APIRequestException e) {
//			log.warn("jpushException",e);
//			throw new InsLogicException(ApiCode.SYSTEM_RUN_ERROR,e);
//		}
//	}

	
	@Override
	public JsonObject sendPush(String title, String message, String... tags) {
		try {
			PushResult result = jpushClient.sendPush(createGroupPush(title, message, tags));
			if(result==null) {
				return null;
			}
			if (log.isInfoEnabled()) {
				log.info("sendPush(String, String, String) - title={}, message={}, tags={}, result={}", title, message, tags, result);
			}
			return gson.toJsonTree(result).getAsJsonObject();
		} catch (APIConnectionException | APIRequestException e) {
			log.warn("jpushException",e);
			throw new CustomException("发送失败", e);
		}
	}

	@Override
	public JsonObject sendPushOnTime(String name, long time, String title, String message, String... tags)  {
		try {
			String time_str= DateFormatUtils.format(time, TIME_FORMAT_VALUE, TimeZone.getDefault());
			PushPayload croupPush = createGroupPush(title, message, tags);
			
			log.info("sendPushOnTime PushPayload = {}",croupPush.toString());
			
			ScheduleResult result = jpushClient.createSingleSchedule(name, time_str, croupPush);
			if(result==null) {
				return null;
			}
			
			if (log.isInfoEnabled()) {
				log.info("sendPushOnTime(String, long, String, String, String) - name={}, time={}, title={}, message={}, tags={}, time_str={}, result={}", name, time, title, message, tags, time_str, result); //$NON-NLS-1$
			}
			
			return gson.toJsonTree(result).getAsJsonObject();
		} catch (APIConnectionException | APIRequestException e) {
			log.warn("jpushException",e);
			throw new CustomException("发送失败", e);
		}
	}
	
	public PushPayload createAlertAll(String alert,String title,String userType,long userId) {
		return PushPayload.newBuilder()
                .setPlatform(Platform.all())
    			.setAudience(Audience.alias(StringFormater.format("{}#{}", userType,userId)))
                .setNotification(Notification.android(alert, title, null))
                .build();
	}

	
//	@Override
//	public JsonObject sendPushOnTime(String name, long time, String title, String message, PushReceiverInfo pushReceiverInfo)  {
//		try {
//
//			String time_str= DateFormatUtils.format(time, TIME_FORMAT_VALUE, TimeZone.getDefault());
//
//			log.info("sendPushOnTime name={}, time={}, title={}, message={}, userType={}, userId={}, time_str={}",
//					name, time, title, message, pushReceiverInfo.getReceiverType(), pushReceiverInfo.getReceiverId(), time_str); //$NON-NLS-1$
//
//			ScheduleResult result = jpushClient.createSingleSchedule(name,time_str,createUserPush(title, message, pushReceiverInfo.getReceiverType(), pushReceiverInfo.getReceiverId()));
//			if(result==null) {
//				return null;
//			}
//
//			if (log.isInfoEnabled()) {
//				log.info("sendPushOnTime(String, long, String, String, String, Long) - name={}, time={}, title={}, message={}, userType={}, userId={}, time_str={}, result={}", name, time, title, message, pushReceiverInfo.getReceiverType(), pushReceiverInfo.getReceiverId(), time_str, result); //$NON-NLS-1$
//			}
//
//			return gson.toJsonTree(result).getAsJsonObject();
//		} catch (APIConnectionException | APIRequestException e) {
//			log.warn("jpushException",e);
//			throw new InsLogicException(ApiCode.SYSTEM_RUN_ERROR,e);
//		}
//	}
//

	@Override
	public void deleteSchedule(String scheduleId)  {
		try {
			if (log.isInfoEnabled()) {
				log.info("deleteSchedule(String) - scheduleId={}", scheduleId); //$NON-NLS-1$
			}

			jpushClient.deleteSchedule(scheduleId);
		} catch (APIConnectionException | APIRequestException e) {
			log.warn("jpushException",e);
			throw new CustomException("发送失败", e);
		}
	}
	
	
	@PreDestroy
	@Override
	public void close() throws IOException {
		log.info("jpush close.....");
		jpushClient.close();
	}
	
	public static void main(String[] args) throws Exception {
		String appKey="7c65fa087b76fc24a32fc903";
		String masterSecret="6ace79089941c097f5568240";
		JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance());
		JPushServiceImpl pushServiceImpl=new JPushServiceImpl();
		pushServiceImpl.jpushClient=jpushClient;
//		pushServiceImpl.createGroupPush("测试12", "测试12", ReceiverTag.MEMBER_STUDENT.name());
//		System.out.println(jpushClient.getTagList().tags);
//		pushServiceImpl.sendPushOnTime("教师接收", System.currentTimeMillis()+1000*60, "教师接收1", "教师接收2",PublisherVo.TYPE_TEACHER);
//		pushServiceImpl.sendPushOnTime("学员接收", System.currentTimeMillis()+1000*60, "学员接收1", "学员接收2",PublisherVo.TYPE_USER);
//		pushServiceImpl.sendPushOnTime("会员学员接收", System.currentTimeMillis()+1000*60, "会员学员接收1", "会员学员接收2",ReceiverTag.MEMBER_STUDENT.name());
//		pushServiceImpl.sendPushOnTime("非会员学员接收", System.currentTimeMillis()+1000*60, "非会员学员接收1", "非会员学员接收2",ReceiverTag.NOT_MEMBER_STUDENT.name());
		
//		pushServiceImpl.updateReceiver("160a3797c8998edaa83", ReceiverTag.NOT_MEMBER_STUDENT.name(), 1230427630663036930L, new TreeSet<>());
//		pushServiceImpl.sendPush("hello", "helloWord!收到群里喊一下");
//		pushServiceImpl.sendPushOnTime("ontime", System.currentTimeMillis()+1000*60*5, "定时推送", "定时推送信息");
//		pushServiceImpl.sendPushOnTime("ontime", System.currentTimeMillis()+1000*60*5, "定时推送2", "定时推送信息2", PublisherVo.TYPE_USER, 1230427630663036930L);
//		pushServiceImpl.sendPushOnTime("测试后台定时群组推送", System.currentTimeMillis()+1000*60,
//				"后台定时推送给会员学生Title", "后台定时推送给会员学生content", ReceiverTag.MEMBER_STUDENT.name());
//		pushServiceImpl.sendPush("群组推送", "群组推送", PublisherVo.TYPE_USER);
//		pushServiceImpl.sendPush("用户推送信息", "用户推送信息", PublisherVo.TYPE_USER, 1230427630663036930L);
		pushServiceImpl.close();
	}
}
